//
//  MainViewController.m
//  AppYing
//
//  Created by appying_wxj on 14/11/3.
//  Copyright (c) 2014年 appying_wxj. All rights reserved.
//

#import "MainViewController.h"
#import "DetailedViewController.h"
#import "NewsCustomCell.h"
#import "UMSocialWechatHandler.h"// 微信
#import "UMSocialQQHandler.h"// qq
#import "UMSocial.h"
#import "MMLocationManager.h"// 获取地理位置
#import "AllRequsetData.h"// 请求网络
#import "MJRefresh.h"// 下拉刷新第三方


@interface MainViewController ()

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   
    self.view.backgroundColor = [UIColor colorWithRed:0.87 green:0.87 blue:0.87 alpha:1];
    self.titleLab.text = @"译文";
    [self initUI];
    
    if ([AllRequsetData checkNet]) {
        [self getGeographicalPosition];
         [_mainTableView reloadData];
        [self setupRefresh];// 集成刷新表格
    }
}

-(void)initUI{
    [self.leftButton setBackgroundImage:[UIImage imageNamed:@"image_sousuo@2x"] forState:UIControlStateNormal];
    //    [self.leftButton setTitle:@"返回" forState:UIControlStateNormal];
    self.leftButton.frame = CGRectMake(0, 20, 60, 44);
    [self.leftButton addTarget:self action:@selector(searchButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.rigthButton setBackgroundImage:[UIImage imageNamed:@"image_gerenCenter@2x"] forState:UIControlStateNormal];
    self.rigthButton.frame = CGRectMake(kScreen_Width-60, 20, 60, 44);
    [self.rigthButton addTarget:self action:@selector(IndividualCenterButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    // 表格的初始化
    self.mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreen_Width, kScreen_Height-64) style:UITableViewStylePlain];
    self.mainTableView.backgroundColor = [UIColor colorWithRed:0.87 green:0.87 blue:0.87 alpha:1];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    self.mainTableView.rowHeight = 350;
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.mainTableView.separatorStyle = NO; // 去掉分割线
    [self.view addSubview:self.mainTableView];
}

#pragma mark~~~~~~~~~~~~~获取地理位置~~~~~~~~~~~~~
// 获取地理位置
-(void)getGeographicalPosition{
    // 获取地理位置
    __block __weak MainViewController *wself = self;
    [[MMLocationManager shareLocation] getAddress:^(NSString *addressString) {
        [wself setLabelText:addressString];
    }];
}
// 获取地理位置
-(void)setLabelText:(NSString *)text
{
    // 地理位置的获取
    NSString *location = [NSString stringWithFormat:@"%@",text];
    //    NSLog(@"______**********_________text %@",location);
    NSString *bigString, *smallString;
    bigString = [location substringToIndex:3];// 字符串的截取前面4位
    smallString = [location substringWithRange:NSMakeRange(9,3)];// 截取中鼎范围内的字符串 NSMakeRange(排行第几位,共几位)
    
    self.positionString = [[NSString alloc] initWithFormat:@"%@%@",bigString,smallString];
    NSLog(@"您当前的位置是——————————————%@",_positionString);
}
#pragma mark~~~~~~~~~~~~~uitableView dataSource~~~~~~~~~~~~~
// 返回多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identify = @"cell";
    _cell = [tableView dequeueReusableCellWithIdentifier:identify];
    
    if(_cell == nil)
    {
        _cell = [[NewsCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
    }
    else{
        while ([_cell.contentView.subviews lastObject]!=nil) {
            [(UIView*)[_cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    _cell.backgroundColor = [UIColor colorWithRed:0.87 green:0.87 blue:0.87 alpha:1];
    _cell.selectionStyle = UITableViewCellSelectionStyleNone;
    _cell.userInteractionEnabled = YES;
   
    
    // 文章标题的自定义 
    [_cell layoutCell:nil];

    // 分享的按钮
    _cell.shareButton.tag = indexPath.row+100;
    [_cell.shareButton addTarget:self action:@selector(shareButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //评论的按钮
    _cell.messageButton.tag = indexPath.row+200;
    [_cell.messageButton addTarget:self action:@selector(messageButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
    //收藏的按钮]
    _cell.collectButton.tag = indexPath.row+300;
    [_cell.collectButton setBackgroundImage:[UIImage imageNamed:@"image_shoucang1@2x"] forState:UIControlStateNormal];
    [_cell.collectButton addTarget:self action:@selector(collectButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return _cell;
}
-(void)btntest:(UIButton *)sender
{
    NSLog(@"点击了测试按钮");
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    dispatch_async(dispatch_get_main_queue(), ^
                   {
                       NSLog(@"---------您点击的时第%d行",indexPath.row);
                       DetailedViewController *detaileds= [[DetailedViewController alloc] init];
                       detaileds.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
                       detaileds.positionStrings = self.positionString;
                       [self presentViewController:detaileds animated:YES completion:nil];
                   });
}
#pragma mark~~~~~~~~~~~~~下拉刷新的方法~~~~~~~~~~~~~
// 建立刷新控件
- (void)setupRefresh{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.mainTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.mainTableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    //自动刷新(一进入程序就下拉刷新)
    //[self.tableView headerBeginRefreshing];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.mainTableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.mainTableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.mainTableView.headerRefreshingText = @"正在刷新中";
    
    self.mainTableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.mainTableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.mainTableView.footerRefreshingText = @"正在加载中";
}
// 下拉刷新的方法
/**
 *  数据的懒加载
 */
- (NSMutableArray *)fakeData {
    if (!_fakeData) {
        self.fakeData = [NSMutableArray array];
        for (int i = 0; i<12; i++) {
            [self.fakeData addObject:self.string];
        }
    }
    return _fakeData;
}
-(NSString *)string {
    NSString *string = [NSString stringWithFormat:@"%d",arc4random_uniform(10000)];
    return string;
}
- (void)headerRereshing{
    // 1.添加假数据
    for (int i = 0; i<5; i++) {
        [self.fakeData insertObject:[self string] atIndex:0];
    }
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.mainTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.mainTableView headerEndRefreshing];
    });
}
// 上提加载的方法
- (void)footerRereshing {
    // 1.添加假数据
    for (int i = 0; i<5; i++) {
        [self.fakeData addObject:[self string]];
    }
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.mainTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.mainTableView footerEndRefreshing];
    });

}


#pragma mark~~~~~~~~~~~~~搜索条开始~~~~~~~~~~~~~

// 导航条左边搜索按钮
-(void)searchButtonClick:(UIButton *)sender{
    //  [_mainTableView setHidden:YES];//隐藏主表格
    [_navBG setHidden:YES];
    
    // 搜索界面的背景
    _searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Kwidth, kheight)];
    _searchView.backgroundColor =[UIColor colorWithRed:0.16 green:0.17 blue:0.21 alpha:0.7];
    [self.view addSubview:_searchView];
    
    
    
    _BackgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Kwidth, 64)];
    _BackgroundView.backgroundColor = [UIColor colorWithRed:0.16 green:0.17 blue:0.21 alpha:1];
    [_searchView addSubview:_BackgroundView];

    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(60, 27, 200, 30)];
    titleLab.text = @"搜索中心";
    titleLab.textColor = [UIColor whiteColor];
    titleLab.font = [UIFont systemFontOfSize:18];
    titleLab.textAlignment = NSTextAlignmentCenter;
    [_BackgroundView addSubview:titleLab];
    
//    UIView *bgView= [[UIView alloc] initWithFrame:CGRectMake(0, 64, kScreen_Width, 50)];
//    bgView.backgroundColor = [UIColor colorWithRed:0.79 green:0.79 blue:0.81 alpha:1];
//    [_searchView addSubview:bgView];
    
    // 取消按钮
    _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _cancelButton.frame = CGRectMake(0, 25, 60, 40);
    _cancelButton.backgroundColor = [UIColor clearColor];
    [_cancelButton setTitle:@"返回" forState:UIControlStateNormal];
    _cancelButton.titleLabel.font=[UIFont systemFontOfSize:16];
    [_cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_cancelButton addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_BackgroundView addSubview:_cancelButton];
    
    
    // 搜索框的界面设置
    _bar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, kScreen_Width, 50)];
    _bar.backgroundColor = [UIColor clearColor];
    //[[_bar.subviews objectAtIndex:0]removeFromSuperview];//去掉搜索框的背景色
    _bar.placeholder = @"请输入搜索的内容";
    [_searchView addSubview:_bar];
    
    //    //搜索结果展示器
    //    UISearchDisplayController *sdc = [[UISearchDisplayController alloc] initWithSearchBar:_bar contentsController:self];
    //    //讲搜索结果展示器的代理设为self
    //    sdc.delegate = self;
    //
    //    //讲搜索结果tableView的数据源和代理设为self
    //    sdc.searchResultsDataSource = self;
    //    sdc.searchResultsDelegate = self;
    //
    
    
}

#pragma mark- searchDisplay 搜索条的代理方法
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption{
    return YES;
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    searchBar.showsScopeBar = YES;
    [searchBar sizeToFit];
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    searchBar.showsScopeBar = NO;
    [searchBar sizeToFit];
    [searchBar setShowsCancelButton:NO animated:YES];
    return YES;
}
// 搜索界面取消的按钮的设置
-(void)cancelButtonClick:(UIButton *)sender{
    [_mainTableView setHidden:NO];//隐藏主表格
    [_navBG setHidden:NO];
    [_searchView removeFromSuperview];
}

#pragma mark~~~~~~~~~~~~~ButtonClick~~~~~~~~~~~~~
// 分享的按钮
-(void)shareButtonClick:(UIButton *)sender{
    //状态提示框
    _greyView = [[UIView alloc]initWithFrame:
                 CGRectMake(0, 0, Kwidth, kheight)];
    _greyView.backgroundColor =
    [UIColor colorWithRed:70.0 / 255.0 green:70.0 / 255.0 blue:70.0 / 255.0 alpha:0.5];
    [self.view addSubview:_greyView];
    
    UIView *alertView = [[UIView alloc]initWithFrame:CGRectMake(10, kheight, 300, 100)];
    alertView.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:0.8];
    [alertView.layer setMasksToBounds:YES];
    [alertView.layer setCornerRadius:10.0]; //设置矩形四个圆角半径
    [alertView.layer setBorderWidth:1.0];
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0, 0, 0, 0 });
    [alertView.layer setBorderColor:colorref];//边框颜色
    
    //qq按钮
    UIButton *qqButton = [UIButton buttonWithType:UIButtonTypeCustom];
    qqButton.frame = CGRectMake(35, 30, 40, 40);
    [qqButton setImage:[UIImage imageNamed:@"image_QQ.png"] forState:UIControlStateNormal];
    [qqButton addTarget:self action:@selector(qqButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    qqButton.tag = 100;
    [alertView addSubview:qqButton];
    
    //微信按钮
    UIButton *weiXinButton = [UIButton buttonWithType:UIButtonTypeCustom];
    weiXinButton.frame = CGRectMake(100, 30, 40, 40);
    [weiXinButton setImage:[UIImage imageNamed:@"sns_icon_22.png"] forState:UIControlStateNormal];
    [weiXinButton addTarget:self action:@selector(weiXinButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    weiXinButton.tag = 101;
    [alertView addSubview:weiXinButton];
    
    //  取消的按钮
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelButton.frame = CGRectMake(10, kheight+120, 300, 40);
    [cancelButton.layer setMasksToBounds:YES];
    [cancelButton.layer setCornerRadius:10.0]; //设置矩形四个圆角半径
    [cancelButton.layer setBorderWidth:1.0];
    [cancelButton.layer setBorderColor:colorref];//边框颜色
    cancelButton.backgroundColor = [UIColor whiteColor];
    [cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    cancelButton.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:0.8];
    [cancelButton addTarget:self action:@selector(backViewController:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [UIView animateWithDuration:0.3 animations:^{
        alertView.frame=CGRectMake(10, kheight-170, 300, 100);
        cancelButton.frame = CGRectMake(10, kheight-60, 300, 40);
        [_greyView addSubview:cancelButton];
        [_greyView addSubview:alertView];
    }completion:^(BOOL finished) {
        
    }];
}
// 收藏的按钮
-(void)collectButtonClick:(UIButton *)sender{
    if (!collects) {// 已收藏
        [sender setBackgroundImage:[UIImage imageNamed:@"image_cang@2x"] forState:UIControlStateNormal];
            
    }else{// 取消收藏
        [sender setBackgroundImage:[UIImage imageNamed:@"image_shoucang1@2x"] forState:UIControlStateNormal];
    }
        collects =!collects;
}
// 评论的按钮
-(void)messageButtonClick:(UIButton *)sender{

    DetailedViewController *detaileds= [[DetailedViewController alloc] init];
    detaileds.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    detaileds.positionStrings = self.positionString;
    [self presentViewController:detaileds animated:YES completion:nil];

}

// 分享界面的取消按钮
-(void)backViewController:(UIButton *)sender{
    [_greyView removeFromSuperview];
}
// 点击QQ按钮
-(void)qqButtonClick:(UIButton *)sender{
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQQ] content:@"分享文字" image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
    
}
//点击微信上的按钮
-(void)weiXinButtonClick:(UIButton *)sender{
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatSession] content:@"分享内嵌文字" image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            NSLog(@"分享成功！");
        }
    }];
    
}
// 导航条右边个人中心按钮
-(void)IndividualCenterButtonClick:(UIButton *)sender{
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
